package com.appkubes.fintech.admin.application.bill.service.impl;


import cn.hutool.core.date.DateUtil;
import com.appkubes.fintech.admin.application.bill.dao.RentBillHeaderDao;
import com.appkubes.fintech.admin.application.bill.dao.RentBillLinesDao;
import com.appkubes.fintech.admin.application.bill.entity.dto.*;
import com.appkubes.fintech.admin.application.bill.entity.vo.RentBillHeaderRequest;
import com.appkubes.fintech.admin.application.bill.service.IRepayService;
import com.appkubes.fintech.admin.application.bill.service.RentBillHeaderService;
import com.appkubes.fintech.admin.application.order.dao.RentOrderDao;
import com.appkubes.fintech.common.response.Response;
import com.appkubes.fintech.common.util.ConversionUtil;
import com.appkubes.fintech.core.po.*;
import com.appkubes.fintech.core.pojo.FintechCreditMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/*
 * 账单列表
 * @author    xqc
 * @date    2020/01/03 19:02:40
 */
@Service
@Slf4j
@Data
public class RentBillHeaderServiceImpl implements RentBillHeaderService {

    @Resource
    RentBillHeaderDao rentBillHeaderDao;
    @Resource
    RentOrderDao rentOrderDao;
    @Resource
    private RentBillLinesDao linesDao;
    @Resource
    private IRepayService repayService;
    @Resource
    private FintechCreditMapper creditMapper;



    @Override
    public PageInfo<RentBillHeaderDTO> queryPage(RentBillHeaderRequest rentBillHeaderRequest) {
        PageHelper.startPage(rentBillHeaderRequest.getPage(), rentBillHeaderRequest.getPageSize());
        List<RentBillHeaderDTO> demoList = rentBillHeaderDao.queryPage(rentBillHeaderRequest);
        demoList.forEach(e->{
            FintechCreditExample example=new FintechCreditExample();
            example.createCriteria().andUserKeyEqualTo(e.getUserKey());
            List<FintechCredit> credit=creditMapper.selectByExample(example);
            if(credit!=null&&credit.size()>0){
                e.setRiskRemark(credit.get(0).getApproval());
            }
        });
        PageInfo pageInfo = new PageInfo(demoList);
        return new PageInfo<>(demoList);
    }


    @Override
    public Response update(RentBillHeaderRequest rentBillHeaderRequest) {
        if (StringUtils.isBlank(rentBillHeaderRequest.getBillKey())) {
            return Response.fail("主键不能为空");
        }
        FintechRentBillHeader old = rentBillHeaderDao.selectByPrimaryKey(rentBillHeaderRequest.getBillKey());
        if (old == null) {
            return Response.fail("对象不存在");
        }
        BeanUtils.copyProperties(rentBillHeaderRequest, old, "id", "createTime", "updateTime");
        rentBillHeaderDao.updateByPrimaryKey(old);
        return Response.success();
    }


    @Override
    public Response deleteRentBillHeader(String id) {
        if (StringUtils.isBlank(id)) {
            return Response.fail("主键不能为空");
        }
        FintechRentBillHeader rentBillHeader = rentBillHeaderDao.selectByPrimaryKey(id);
        if (rentBillHeader == null) {
            return Response.fail("对象不存在");
        }
        rentBillHeaderDao.deleteByPrimaryKey(rentBillHeader.getBillKey());
        return Response.success();
    }

    @Override
    public Response<RentBillHeaderDTO> getById(String id) {
        FintechRentBillHeader rentBillHeader = rentBillHeaderDao.selectByPrimaryKey(id);
        FintechRentOrder order=rentOrderDao.selectByPrimaryKey(rentBillHeader.getOrderKey());
        RentBillHeaderDTO rentBillHeaderDTO = new RentBillHeaderDTO();
        BeanUtils.copyProperties(rentBillHeader, rentBillHeaderDTO);
        FintechRentBillLinesExample example = new FintechRentBillLinesExample();
        example.createCriteria().andBillKeyEqualTo(id);
        example.setOrderByClause(" period ");
        List<FintechRentBillLines> linesList = linesDao.selectByExample(example);
        Integer beforePayAmt=0;
        for(FintechRentBillLines e :linesList) {
            if (e.getPeriod() <= rentBillHeader.getUnpayPeriods()
                    ||e.getPeriodStartDate().getTime()<new Date().getTime()) {
                beforePayAmt = beforePayAmt + e.getUnpayAmount();
                beforePayAmt = beforePayAmt + e.getUnpayFineAmount();
                beforePayAmt = beforePayAmt + e.getUnpayInterestAmount();
            }
            else{
                beforePayAmt = beforePayAmt + e.getUnpayAmount();
            }
        }
        beforePayAmt=beforePayAmt+order.getBuyOutAmount();
        rentBillHeaderDTO.setBeforePayAmt(new BigDecimal(beforePayAmt/100));
        List<RentBillLinesDTO> responseList = ConversionUtil.ofList(linesList, RentBillLinesDTO.class);
        rentBillHeaderDTO.setLinesList(responseList);
        return Response.success(rentBillHeaderDTO);

    }

    @Override
    public void deleteById(String id) {
        rentBillHeaderDao.deleteByPrimaryKey(id);
    }
    @Override
    public Response<List<BillReportDTO>> billReport(BillReportVO vo){
       List<BillReportDTO> list =rentBillHeaderDao.billReport(vo).stream().map(e->{
           e.setRepayAmt(e.getRepayAmt()/100);
           e.setRepayFineAmt(e.getRepayFineAmt()/100);
           e.setRepayInterestAmt(e.getRepayInterestAmt()/100);
           e.setRepayTotalAmt(e.getRepayAmt()+e.getRepayInterestAmt()+e.getRepayFineAmt());

           e.setUnpayAmt(e.getUnpayAmt()/100);
           e.setUnpayIntegerestAmt(e.getUnpayIntegerestAmt()/100);
           e.setUnpayFineAmt(e.getFineAmt()/100);
           e.setUnpayTotalAmt(e.getUnpayAmt()+e.getUnpayIntegerestAmt()+e.getUnpayFineAmt());

           e.setPayAmt(e.getPayAmt()/100);
           e.setInterestAmt(e.getInterestAmt()/100);
           e.setFineAmt(e.getFineAmt()/100);
           e.setTotalAmt(e.getPayAmt()+e.getInterestAmt()+e.getFineAmt());

           BigDecimal rate=BigDecimal.ZERO;
           rate = new BigDecimal(e.getRepayTotalAmt()).divide(new BigDecimal(e.getTotalAmt()), 2, BigDecimal.ROUND_HALF_UP);
           e.setRepayRate(rate.multiply(new BigDecimal(100)).toString()+"%");
           return e;
       }).collect(Collectors.toList());
       return Response.success(list);
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    @Override
    public Response repay(RepayVO vo){
        if("1".equals(vo.getRepayType())){ // 账期还款
           return  repayService.payPeriod(vo);
        }
        if("2".equals(vo.getRepayType())){ // 账期还款
            return    repayService.payBefore(vo);
        }
        if("3".equals(vo.getRepayType())){ // 账期还款
            return    repayService.payBeforeAndBuyOut(vo);
        }
        if("4".equals(vo.getRepayType())){ // 账期还款
            return    repayService.buyOut(vo);
        }
        return Response.fail("类型错误");
    }
}
